package com.itheima.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.exception.MyException;
import com.itheima.common.result.JsonResult;
import com.itheima.entity.Setmeal;
import com.itheima.entity.SetmealDish;
import com.itheima.entity.dto.SetmealDto;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhengbinghua
 * @since 2023-03-02
 */
@RestController
@RequestMapping("/setmeal")
@Api(tags = "套餐管理")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private SetmealDishService setmealDishService;
    @GetMapping("{id}")
    @ApiOperation(value = "套餐详情")
    public JsonResult getSetmealInfo(@PathVariable String id ){
        //查询套餐
        Setmeal setmeal = setmealService.getById(id);
        if (setmeal==null){
            throw new MyException(404, "套餐不存在！");
        }
        SetmealDto setmealDto = new SetmealDto();
        BeanUtil.copyProperties(setmeal, setmealDto);
        //查询套餐内菜品
        List<SetmealDish> list = setmealDto.getSetmealDishList();
        //在setmeelDIsh列表里面添加dishId
        List<SetmealDish> setmealDishes = list.stream().map(setmealDish -> {
            setmealDish.setSetmealId(setmeal.getId());
            return setmealDish;
        }).collect(Collectors.toList());
        //添加到SetmealDish表里面
        setmealDishService.saveBatch(setmealDishes);
        //返回前端
        return JsonResult.success(setmealDto);
    }
/***查询套餐列表
 *
 * @return*/
@GetMapping("list")
@ApiOperation(value = "查询套餐列表")
    public JsonResult getSetmealList(String categoryId, String status ){
    //前端判断状态是否是"0"
    if ("0".equals(status)){
        throw new MyException(404, "菜品不能被查询！");
    }
    LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(Setmeal::getCategoryId,categoryId);
    wrapper.eq(Setmeal::getStatus,"1");
    List<Setmeal> list = setmealService.list(wrapper);
    return JsonResult.success(list);
}
}
